package top.hiai.service.impl;

import cn.hutool.core.map.MapUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.hiai.common.dto.UserInfoDto;
import top.hiai.common.result.JsonResult;
import top.hiai.common.utils.TokenUtil;
import top.hiai.entity.User;
import top.hiai.mapper.UserMapper;
import top.hiai.service.UserService;

import java.util.Date;

/**
 * @Author hkq
 * @Email goodsking@163.com
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public JsonResult userAuth(String openid) throws Exception {
        User user = null;
        user = userMapper.findByOpenid(openid);
        //用户不存在的情况
        if (null == user) {
            //用户不存在添加一条数据
            user = User.builder()
                    .openid(openid)
                    .addtime(new Date())
                    .build();
            userMapper.insert(user);
        }
        user = userMapper.findByOpenid(openid);
        //用户存在的情况下
        String token = TokenUtil.sign(user);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValueAsString(token);

        return JsonResult.succ(MapUtil.builder()
                .put("userInfo", user)
                .put("token", token)
                .map());
    }

    @Override
    public User getUserByOpenid(String openid) {
        return userMapper.findByOpenid(openid);
    }

    @Override
    public User getUserById(Integer userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public UserInfoDto getUserInfo(int userId) {
        return userMapper.getUserInfo(userId);
    }
}
